﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using DevExpress.XtraGrid.Views.Base;
using NAGFwk.UI;
using SilkeyERP.BL;
using SilkeyERP.Model;
using System.Globalization;

namespace SilkeyERP.UI.Entities.Customers
{
    public partial class CustomEditContentView : BaseCustomEditForm
    {

        private Model.Customer current;
        private Shared.ProductChooser productChooser = new Shared.ProductChooser();
        public CustomEditContentView()
        {
            InitializeComponent();
            FillDataSources();
            xtcCustomEditContentView.SelectedTabPageIndex = 0;
            btnProductSearch.FormChooserType = productChooser;
            btnProductSearch.OnSelected += btnProductSearch_OnSelected;
            streetTextEdit.Enabled = false;
        }
        void btnProductSearch_OnSelected(List<dynamic> SelectedItems)
        {
            AddToSalesPriceListByCustomer(SelectedItems);
        }

        private void AddToSalesPriceListByCustomer(List<dynamic> SelectedProducts)
        {
            var oriResult = ((List<Model.SalesPriceListByCustomer>)salesPriceListByCustomerBindingSource.DataSource);
            foreach (Model.Products SelectedItem in SelectedProducts)
                if (!oriResult.Any(x => x.ProductID == SelectedItem.ProductID))
                    salesPriceListByCustomerBindingSource.Add(new Model.SalesPriceListByCustomer()
                    {
                        CustomerID = current.CustomerID,
                        CurrentPriceWOutTax = 0,
                        CurrentPriceWTax = 0,
                        ProductID = SelectedItem.ProductID,
                        TaxID = 1
                    });
        }

        private void FillDataSources()
        {
            cityBindingSource.DataSource = new CityController().GetAll();
            customerTypeBindingSource.DataSource = new CustomerTypeController().GetAll();
            paymentMethodBindingSource.DataSource = new PaymentMethodController().GetAll();
            salesPersonBindingSource.DataSource = new SalesPersonController().GetAll();
            taxBindingSource.DataSource = new TaxController().GetAll();
            taxBindingSource1.DataSource = new TaxController().GetAll();
            taxFigureBindingSource.DataSource = new TaxFigureController().GetAll();
            salesPriceListBindingSource.DataSource = new SalesPriceListController().GetAll();
            provinceBindingSource.DataSource = new ProvinceController().GetAll();

        }

        private void EnablextpPriceListByProducts(int SalesPriceListID)
        {
            xtpPriceListByProducts.PageVisible = (SalesPriceListID != int.MinValue);

            if (SalesPriceListID != int.MinValue)
                productChooser.Query = new BL.ProductsController().GetAll().AsQueryable().Where(x => x.SalesPriceListDetails.Any(y => y.SalesPriceListID == SalesPriceListID));
        }

        private void gridView2_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            if (((Model.SalesPriceListByCustomer)e.Row).ProductID == int.MinValue)
            {
                e.Valid = false;
                e.ErrorText = "Debe Seleccionar un Producto";
            }

            if (((List<Model.SalesPriceListByCustomer>)salesPriceListByCustomerBindingSource.DataSource).Where(x => x.ProductID == ((Model.SalesPriceListByCustomer)e.Row).ProductID).Count() > 1)
            {
                e.Valid = false;
                e.ErrorText = "El Producto seleccionado ya existe en la grilla. ";
            }
        }

        public void InitData(ref Model.Customer currentCustomer)
        {
            if (currentCustomer.SalesPriceList != null)
                salesPriceListDetailsBindingSource.DataSource = currentCustomer.SalesPriceList.SalesPriceListDetails;

            var _currentCustomerSalesPriceListByCustomer = new List<Model.SalesPriceListByCustomer>();
            if (currentCustomer.SalesPriceListByCustomer.Count != 0)
                _currentCustomerSalesPriceListByCustomer.AddRange(currentCustomer.SalesPriceListByCustomer);
            salesPriceListByCustomerBindingSource.DataSource = _currentCustomerSalesPriceListByCustomer;
            currentCustomer.SalesPriceListByCustomer = _currentCustomerSalesPriceListByCustomer;

            var _currentCustomerPhones = new List<Model.Phones>();
            if (currentCustomer.Phones.Count != 0)
                _currentCustomerPhones.AddRange(currentCustomer.Phones);
            phonesBindingSource.DataSource = _currentCustomerPhones;
            currentCustomer.Phones = _currentCustomerPhones;

            var _currentCustomerEmail = new List<Model.Email>();
            if (currentCustomer.Email.Count != 0)
                _currentCustomerEmail.AddRange(currentCustomer.Email);
            emailBindingSource.DataSource = _currentCustomerEmail;
            currentCustomer.Email = _currentCustomerEmail;

            var _currentCustomerAddress = new List<Model.Address>();
            if (currentCustomer.Address.Count != 0)
                _currentCustomerAddress.AddRange(currentCustomer.Address);
            addressBindingSource.DataSource = _currentCustomerAddress;
            currentCustomer.Address = _currentCustomerAddress;

            current = currentCustomer;

            if (IsEdit)
            {
                provinceIDSpinEdit.EditValue = currentCustomer.City.ProvinceID;
                EnablextpPriceListByProducts(current.SalesPriceListID);
                txtCustomerCode.Enabled = false;
                if (current.Address.Count > 0)
                {
                    var currentDefaultAddress = current.Address.Single(x => x.Order == 0);
                    streetTextEdit.Text = string.Format("{0}: {1} {2}", currentDefaultAddress.Description, currentDefaultAddress.Street, currentDefaultAddress.Number);
                }
                else
                    streetTextEdit.Text = string.Empty;

                productsBindingSource.DataSource = new ProductsController().GetAll().Where(x => x.SalesPriceListDetails.Any(y => y.SalesPriceListID == current.SalesPriceListID));
                productsBindingSource1.DataSource = new ProductsController().GetAll().Where(x => x.SalesPriceListDetails.Any(y => y.SalesPriceListID == current.SalesPriceListID));
            }

            if (IsNew)
                current.SetNextAvailableCustomerCode();
        }

        private void OthersGridView_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (e.Row.GetType() == typeof(Model.Address))
            {
                var typedRow = (Model.Address)e.Row;

                if (string.IsNullOrEmpty(typedRow.Description))
                {
                    e.ErrorText = Properties.Resources.ErrorAddressDescriptionRequired;
                    e.Valid = false;
                }
                if (string.IsNullOrEmpty(typedRow.Street))
                {
                    e.ErrorText = Properties.Resources.ErrorAddressStreetRequired;
                    e.Valid = false;
                }

                if (string.IsNullOrEmpty(typedRow.Number.ToString()))
                {
                    e.ErrorText = "Numero en Direccion es requerido.";
                    e.Valid = false;
                }

                if (new AddressController().GetAll().Exists(x => x.Order == typedRow.Order && x.Customer.Any(y => y.CustomerID == current.CustomerID)))
                {
                    e.ErrorText = string.Format("Ya existe una direccion con el orden {0}", typedRow.Order);
                    e.Valid = false;
                }
            }
            else if (e.Row.GetType() == typeof(Model.Email))
            {
                var typedRow = (Model.Email)e.Row;

                if (string.IsNullOrEmpty(typedRow.Description))
                {
                    e.ErrorText = Properties.Resources.ErrorEmailDescriptionRequired;
                    e.Valid = false;
                }
                if (string.IsNullOrEmpty(typedRow.Email1))
                {
                    e.ErrorText = Properties.Resources.ErrorEmailRequired;
                    e.Valid = false;
                }

                if (new EmailController().GetAll().Exists(x => x.Order == typedRow.Order && x.Customer.Any(y => y.CustomerID == current.CustomerID)))
                {
                    e.ErrorText = string.Format("Ya existe un Email con el orden {0}", typedRow.Order);
                    e.Valid = false;
                }
            }
            else if (e.Row.GetType() == typeof(Model.Phones))
            {
                var typedRow = (Model.Phones)e.Row;

                if (string.IsNullOrEmpty(typedRow.Description))
                {
                    e.ErrorText = Properties.Resources.ErrorPhonesDescriptionRequired;
                    e.Valid = false;
                }
                if (string.IsNullOrEmpty(typedRow.Number.ToString()))
                {
                    e.ErrorText = Properties.Resources.ErrorPhoneNumberRequired;
                    e.Valid = false;
                }

                if (new PhonesController().GetAll().Exists(x => x.Order == typedRow.Order && x.Customer.Any(y => y.CustomerID == current.CustomerID)))
                {
                    e.ErrorText = string.Format("Ya existe un Telefono con el orden {0}", typedRow.Order);
                    e.Valid = false;
                }

            }
        }

        private void cityIDSpinEdit_EditValueChanged(object sender, EventArgs e)
        {
            if (cityIDSpinEdit.ItemIndex != -1)
            {
                var city = new CityController().GetCity(int.Parse(cityIDSpinEdit.EditValue.ToString()));
                provinceIDSpinEdit.EditValue = city.ProvinceID;
            }
        }

        private void rilueTax_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListByCustomerBindingSource.Current != null && (int)((DevExpress.XtraEditors.LookUpEdit)(sender)).ItemIndex != -1)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListByCustomer)salesPriceListByCustomerBindingSource.Current;
                var SelectedTaxValue = new BL.TaxController().GetTax((int)((DevExpress.XtraEditors.LookUpEdit)(sender)).EditValue).TaxValue;
                typedPriceListDetailsBindingSource.CurrentPriceWTax = typedPriceListDetailsBindingSource.CurrentPriceWOutTax * decimal.Parse("1." + SelectedTaxValue.ToString().Replace(".", ""));
            }
        }

        private void riseCurrentPriceWTax_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListByCustomerBindingSource.Current != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListByCustomer)salesPriceListByCustomerBindingSource.Current;
                if (typedPriceListDetailsBindingSource.TaxID != 0)
                    UpdateCurrentPriceWOutTax((decimal)((DevExpress.XtraEditors.SpinEdit)sender).EditValue, typedPriceListDetailsBindingSource.TaxID);
            }
        }

        private void riseCurrentPriceWOutTax_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListByCustomerBindingSource.Current != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListByCustomer)salesPriceListByCustomerBindingSource.Current;
                if (typedPriceListDetailsBindingSource.TaxID != 0)
                    UpdateCurrentPriceWTax(typedPriceListDetailsBindingSource,(decimal)((DevExpress.XtraEditors.SpinEdit)sender).EditValue, typedPriceListDetailsBindingSource.TaxID);
            }
        }

        private void UpdateCurrentPriceWOutTax(decimal CurrentPriceWTax, int TaxID)
        {
            var typedPriceListDetailsBindingSource = (Model.SalesPriceListByCustomer)salesPriceListByCustomerBindingSource.Current;
            var SelectedTaxValue = new BL.TaxController().GetTax(TaxID).TaxValue;
            typedPriceListDetailsBindingSource.CurrentPriceWOutTax = GetValueWOutTax(CurrentPriceWTax, SelectedTaxValue);
        }

        private void UpdateCurrentPriceWTax(Model.SalesPriceListByCustomer current, decimal CurrentPriceWOutTax, int TaxID)
        {            
            var SelectedTaxValue = new BL.TaxController().GetTax(TaxID).TaxValue;
            current.CurrentPriceWTax = GetValueWTax(CurrentPriceWOutTax, SelectedTaxValue);
        }

        private decimal GetValueWOutTax(decimal CurrentPriceWTax, decimal CurrentTaxValue)
        {
            return CurrentPriceWTax / decimal.Parse("1." + CurrentTaxValue.ToString(CultureInfo.InvariantCulture).Replace(".", ""));
        }

        private decimal GetValueWTax(decimal CurrentPriceWOutTax, decimal CurrentTaxValue)
        {
            return CurrentPriceWOutTax * decimal.Parse("1." + CurrentTaxValue.ToString(CultureInfo.InvariantCulture).Replace(".", ""));
        }
     
        private void cboSalesPerson_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            salesPriceListBindingSource.DataSource = new SalesPersonController().GetSalesPerson((int)e.NewValue).SalesPriceList;
        }

        private void cboSalesPriceList_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            int selectedID = (int)e.NewValue;
            if (salesPriceListByCustomerBindingSource.Count > 0)
            {
                if (System.Windows.Forms.MessageBox.Show("El Cliente actual ya tiene productos personalizados asociados y los mismos seran borrados.¿Desea continuar?", Properties.Resources.GeneralMessageTitleWarning, System.Windows.Forms.MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                    OnSalesPriceListChanged(selectedID);
                else
                    e.Cancel = true;
            }
            else
                OnSalesPriceListChanged(selectedID);

        }

        private void OnSalesPriceListChanged(int selectedID)
        {
            EnablextpPriceListByProducts(selectedID);
            productsBindingSource.DataSource = new ProductsController().GetAll().Where(x => x.SalesPriceListDetails.Any(y => y.SalesPriceListID == selectedID));
            productsBindingSource1.DataSource = new ProductsController().GetAll().Where(x => x.SalesPriceListDetails.Any(y => y.SalesPriceListID == selectedID));
            salesPriceListByCustomerBindingSource.Clear();
            salesPriceListDetailsBindingSource.DataSource = new SalesPriceListController().GetSalesPriceList(selectedID).SalesPriceListDetails;
        }
        
    }
}
